var utils = require('../../utils/util.js')
const req = wx.cloud.database().collection('school-request')
const person = wx.cloud.database().collection('person')
wx.cloud.init({
  env: 'data-m4n9e'
})
const db = wx.cloud.database()
const school = db.collection('school-request')
Page({
  data: {
    findex: 0,
    mindex: 0,
    faculty: ['文传', '电气', '外国语', '艺创', '医管', '商学院', '护理系', '会计', '公管', '音乐系', '继教'],
    major: [['网新', '汉语言', '新闻'], ['计算机', '通信工程', '电气工程', '电子信息'], ['英语', '法语', '日语', '韩语', '汉语国际'], ['艺术设计', '数媒', '公共艺术',], ['医检'], ['工商管理', '经济学', '市场营销', '国贸', '旅游管理', '物流管理', '电商', '国际商务', '房地产开发', '文化产业', '金工'], ['护理学'], ['会计学', '财务管理', '审计学'], ['行政管理', '公共关系', '人力'], ['音乐学'], ['商务英语', '法学', '动漫设计', '行政工商', '航空']],
    zhuanye: ['先选院系再选专业'],
    yuanxi: ['点击此处选择院系'],
    textarea: '· 详细说明问题，以便获得更好的回答',
    imagesUrl: [],
    reqType: ['知识', '技能', '运动'],
    stype:['跑步','篮球','羽毛球','跳舞','毽子','乒乓球','轮滑','其它'],
    demand: '运动',
    date: '2019-01-01',
    time: '00:00',
    endDate: '2019-01-01',
    endTime: '01:00',
    socialType: '趣事分享',
    imagesID:[],
    user: [],
    imagesFile:[],
    imgnum :0,
    imagePS: '至多上传6张jpg或png图片',
    creatNumber:0,
    tempFiles:[]
  }, // 注意不要注释这行,为data{}
  // 设置不同的选择呈现不同的表单
  choose: function (event) {
    if ('知识' == event.detail.value) {
      this.setData({ demand: event.detail.value, textarea: '分享一下专业知识吧！' ,imagePS:'至多上传6张jpg或png图片'})
    }

    else if ('技能' == event.detail.value) {
      this.setData({ demand: event.detail.value, textarea: '分享一下技能吧！', imagePS:'有图有真相（至多6张，jpg or png）' })
    }

    else if ('运动' == event.detail.value) {
      this.setData({ demand: event.detail.value, textarea: '分享一下运动趣事吧', imagePS: '有图有真相（至多6张，jpg or png）' })
    }
  },

  // picker选择院系专业
  selectFaculty: function (e) {
    this.setData({ yuanxi: this.data.faculty[e.detail.value], zhuanye: this.data.major[e.detail.value] })
  },
  selectMajor: function (e) {
    this.setData({ mindex: e.detail.value })
  },

  onLoad: function (options) {
    var time = utils.formatTime(new Date()).substring(0, 5)
    var user = wx.getStorageSync('userInfo')
    this.data.openid = options.openid
    if(!user.nickName && !user.avatarUrl){
      this.setData({ authorize: true, signIn:false})
    }
    else{
      this.setData({ authorize:false, signIn: true })
    }
    req.where({
      _openid:options.openid,
      today:time
    }).count({
      success:res=>{
        this.data.creatNumber = res.total
        if(res.total==5){
          wx.showModal({
            title: '提示',
            content: '您今天创建的需求数量已达到5条上限',
            showCancel:false,
            success:res=>{
              wx.reLaunch({
                url: '/pages/index/index'
              })
            }
          })
        }
      }
    })
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5f250d9fbc13524d&secret=46d719bd09ae4a8895b66b9f4ce269c3',
      success: res => {
        this.data.token = res.data.access_token
      },
      fail: res => {
        wx.hideLoading()
        if (res.data.errcode == -1) {
          wx.showToast({
            title: '服务器忙请稍后',
          })
        }
      }
    })
  },


  inputContact: function (e) {
    this.setData({ contact: e.detail.value })
  },

  addimages:function (e)  {
    // 因为在api内部，this对象的setData属性不被允许使用，所以就间接赋值给that方便传输文件路径至wxml的内部状态变量中。
    var that = this  
    var openid = this.data.openid
    var time = utils.formatTime(new Date())
      wx.chooseImage({
        count:6,
        success: function (res) {         
          var tempFilePaths = res.tempFilePaths
          // 使用concat方法，不要只写that.data.imagesUrl .concat(tempFilePaths)，否则不会生效
          if (that.data.imgnum + tempFilePaths.length < 7) {
            that.data.imagesUrl  = that.data.imagesUrl.concat(tempFilePaths)
            // 用于计数
            var figurenum = new Array()
            figurenum = figurenum.concat(tempFilePaths)
            that.data.imgnum += figurenum.length
            that.setData({ tempFiles: that.data.imagesUrl })
          /*
            // 图片鉴黄
            wx.request({
              url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5f250d9fbc13524d&secret=46d719bd09ae4a8895b66b9f4ce269c3',
              success:res=>{
                var token = res.data.access_token
                var url = 'https://api.weixin.qq.com/wxa/img_sec_check?access_token='+token
                wx.request({
                  url: url,
                  method:'POST',
                  data:{
                    media: tempFilePaths
                  },
                  success:res1=>{console.log(res1)}
                })
              }
            })
          */
          // 用临时链接渲染到视图层，后台在默默上传图片，因为变量传输问题（传不到add数据库api里面），所以只好将chooseimage和uploadfile写在一起了。用showToast为图片上传拖延时间
            for (var num = -1; num < that.data.imagesUrl.length;) {
              wx.showLoading({
                title: '请上传完再提交',
              })
              num++
              var name = time.substring(0, 5) + '/' + openid + '_' + num + '_' + Math.floor(Math.random() * 100)
              wx.cloud.uploadFile({
                cloudPath: `${name}.png`,
                filePath: that.data.imagesUrl[num],
                success: res => {
                  that.data.imagesID.push(res.fileID)
                  
                  if (that.data.imagesID.length == that.data.imagesUrl.length){
                    wx.hideLoading()
                  }
                },
                fail: res => {
                  console.error
                }
              })
            }
            
            
          }
          else {
            wx.showModal({
              title: '提示',
              content: '上传的图片数量不能超过6张哦',
            })
          }    
        }
      }) 
  },
  
  delimages: function (e) {
  // 记得要调用delete API节省存储空间  
    
    this.data.imagesID = []
    this.data.imgnum = 0
    this.data.imagesUrl = []
    this.setData({ imagesID: [],tempFiles:[] })
    wx.cloud.deleteFile({
      fileList: this.data.imagesID,
    })
  },

  addContent: function (e) {
    this.setData({ content: e.detail.value })
  },

  checkContactInfo:function(type,info){
    var phoneReg = /^1[3-578]\d{9}$/;
    var mailReg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
    if (type=='手机号码'){
      if(!phoneReg.test(info)){
        return true
      }
      else{
        return false
      }
    }
    else if(type=='email'){
      if(!mailReg.test(info)){
        return true
      }
      else {
        return false
      }
    }
  },

  getuserinfo(res){
    if (res.detail.userInfo) {
      wx.setStorageSync('userInfo', res.detail.userInfo)
      var user = res.detail.userInfo
      this.setData({ authorize: false, signIn: true })
      person.add({
        data:{
          name:user.nickName,
          avatarImage:user.avatarUrl,
          gender: user.gender
        }
      })
    } 
  },

  submitForm(e) {

    var creatTime = utils.formatTime(new Date())
    var today = creatTime.substring(0,5)
    var num = 0
    var res = e.detail.value;
    // 一个if可以对应多个else if 但不能多个if 对应else if，在执行条件分支时会出错
    if (res.requestType == "") {
      wx.showToast({
        title: '请选择需求类型',
        image: 'close-circle.png'
      })
    }

    else if (res.description == "") {
      wx.showToast({
        title: '请说明具体情况',
        image: 'close-circle.png'
      })
    }

    else if (this.data.imagesUrl.length == 0 && res.requestType == '运动') {
      wx.showToast({
        title: '请添加图片',
        image: 'close-circle.png'
      })
    }


    else if (res.requestType == "技能" && this.checkContactInfo(res.contact, res.contactInfo)){
      wx.showToast({
        title: '请检查联系方式',
        image: 'close-circle.png'
      })
    }

    else if (res.requestType == "技能" && res.contactInfo==''){
      wx.showToast({
        title: '请输入联系方式',
        image: 'close-circle.png'
      })
    }

    else if (res.faculty == '点击此处选择院系' && res.requestType=='知识'){
      wx.showToast({
        title: '请选择院系专业',
        image: 'close-circle.png'
      })
    }

    else {
      wx.showLoading({
        title: '正提交数据…',
      })
      // 应微信官方要求增加内容安全审核功能
      var content = e.detail.value.description
      var url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' + this.data.token
      wx.request({
        url: url,
        method: 'POST',
        data: {
          content: content
        },
        // 以前是用res字段产生冲突，要注意参数名
        success: res_check => {
          if (res_check.data.errcode == 87014) {
            wx.hideLoading()
            wx.showModal({
              title: '警告!',
              content: '你创建的消息中含有违法违规内容，请修改好后再提交。',
              showCancel: false
            })
          }
          else{
            var creatNumber = this.data.creatNumber + 1
            var userInfo = wx.getStorageSync('userInfo')
            var date = new Date(creatTime)
            if (userInfo == "") {
              user = ['匿名', 'cloud://data-m4n9e.6461-data-m4n9e-1300093224/project_images/logo.jpg', 0]
            }
            else {
              var user = [userInfo.nickName, userInfo.avatarUrl, userInfo.gender]
            }

            if (res.requestType == '知识') {
              school.add({
                data: {
                  type: res.requestType,
                  description: res.description,
                  imagesUrl: this.data.imagesID,
                  faculty: res.faculty,
                  major: res.major,
                  creatTime: creatTime,
                  click: 0,
                  user: user,
                  date: date,
                  today: today
                },
                success: res => {

                }
              })
            }
            else if (res.requestType == '技能') {
              school.add({
                // 在js数组中，最好还是用驼峰式命名变量，不要带横杠否则很容易被解释错误出现not defined的异常
                data: {
                  type: res.requestType,
                  description: res.description,
                  imagesUrl: this.data.imagesID,
                  contactType: res.contact,
                  contactInfo: res.contactInfo,
                  creatTime: creatTime,
                  click: 0,
                  user: user,
                  date: date,
                  today: today
                }
              })
            }
            else if (res.requestType == '运动') {
              school.add({
                data: {
                  type: res.requestType,
                  description: res.description,
                  imagesUrl: this.data.imagesID,
                  sportType: res.sportType,
                  creatTime: creatTime,
                  click: 0,
                  user: user,
                  date: date,
                  today: today
                }
              })
            }
            wx.hideLoading()
            wx.showToast({
              title: '您已成功创建了需求！',
            })
            // navigateTo,redirect都调用失败出现typeError，只好改用reLauch了。
            wx.reLaunch({
              url: '/pages/index/index'
            })
            wx.showModal({
              title: '提示',
              content: '一天至多创建5条消息，您已经创建了' + creatNumber + '条消息',
              showCancel: false
            })
          }
        },
        fail: res_check => {
          wx.hideLoading()
          if (res_check.data.errcode == -1){
            wx.showToast({
              title: '服务器忙请稍后',
            })
          }
        }
      })
    }
  },
}) // 注意不要注释或删除这行，为page（{}）